#include <iostream>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "comm.h"
using namespace std;

bool Makefifo()
{
    int n = mkfifo(FILENAME, 0666);
    if(n < 0)
    {
        cerr << "errno: " << ", errstring: " << strerror(errno) << endl;
        return false;
    }

    cout << "mafifo success... read" << endl;
    return true;
}


int main()
{
    int n = mkfifo(FILENAME, 0666);
    if(n < 0)
    {
        cerr << "errno: " << errno << ", errstring: " << strerror(errno) << endl;
        return 1;
    }

    cout << "mkfifo success...read" << endl;

    int rfd = open(FILENAME, O_RDONLY);
    if(rfd < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << endl;
        return 2;
    }

    cout << "open fifo success..." << endl;

    char buffer[1024];
    while(true)
    {
        ssize_t s = read(rfd, buffer, sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << "Client say#" << buffer << endl;
        }
        else if(s == 0)
        {
            cout << "client quit, server quit too!" << endl;
            break;
        }
    }

    close(rfd);
    cout << "close fifo success..." << endl;
    return 0;
}